import 'package:flutter/material.dart';
import 'package:flutter_module/beans/data_layer_bean.dart';
import 'package:flutter_module/beans/data_layer_item_bean.dart';
import 'package:flutter_module/beans/element_bean.dart';
import 'package:flutter_module/beans/project_bean.dart';
import 'package:flutter_module/data/data_manager.dart';
import 'package:flutter_module/map/models/ni_geopoint_model.dart';
import 'package:flutter_module/map/models/ni_raster_tile_layer_model.dart';
import 'package:flutter_module/system/library_map.dart';
import 'package:flutter_module/system/log_util.dart';
import 'package:flutter_module/util/event_bus.dart';
import 'package:flutter_module/util/geometry_tool.dart';
import 'package:flutter_module/util/string_utils.dart';
import 'package:flutter_module/views/drawer_pages/base_page.dart';
import 'package:flutter_module/views/drawer_pages/edit_data_page.dart';
import 'package:flutter_module/views/drawer_pages/element_list_page.dart';
import 'package:flutter_module/views/drawer_pages/layer_list_page.dart';
import 'package:flutter_module/views/drawer_pages/base_map_setting_page.dart';
import 'package:flutter_module/views/mapFragmentWidgets/map_bottom_drawer.dart';
import 'package:flutter_module/views/mapFragmentWidgets/map_title_bar.dart';
import 'package:fluttertoast/fluttertoast.dart';
import 'package:flutter_module/util/shared_preferences.dart';
import 'package:flutter_module/views/otherWidgets/my_layer_dialog.dart';
import 'package:flutter_module/views/otherWidgets/my_dialog.dart';
import 'dart:convert' show json, jsonDecode;

import 'package:geocore/data.dart';

///控制抽屉切换的逻辑
class DrawerManagerViewModel with ChangeNotifier {
  // DrawerManagerViewModel() {
  //   LogUtil.instance.printf("DrawerManagerViewModel 初始化");
  // }

  ///用来创建地图的顶部状态栏的context，在[MapTitleBarWidget]创建时会调用[initMapTitleBarContext]进行初始化
  ///在抽屉页面切换时会使用
  late BuildContext _mapTitleBarContext;

  ///抽屉 当前的页面
  BasePage? curPage;

  ///抽屉页面堆栈列表，管理抽页面的切换
  List<BasePage> pageList = [];

  ///顶部状态栏适配器
  MapTitleBarAdapter? mapTitleBarAdapter;

  ///当前的数据图层集合
  List<DataLayer> dataLayerList = [];

  ///项目集合
  List<Project> projectList = [];

  //系统默认支持图层
  List<NIRasterTileLayer> layerList = [];

  //自定义图层
  List<NIRasterTileLayer> otherLayerList = [];

  //是否删除
  bool isDelLayer = false;

  NIRasterTileLayer? selectLayer;

  ///当前正在使用的数据图层
  DataLayer? curDataLayer;

  ///当前正在编辑的数据
  ElementBean? curElementBean;

  List<ElementBean>? dataList;

  DataLayerItem? curItem;

  ///初始化顶部状态栏创建时用到的 context
  void initMapTitleBarContext(BuildContext buildContext) {
    _mapTitleBarContext = buildContext;
    SpHelper.getInstance();
  }

  ///设置地图点击回调
  void initMapOnClickCallback() {
    ///设置地图点击回调
    MapManager.instance.mapController.setMapOnClickCallback((geoPoint) {
      ///
      MapManager.instance.mapController.getBoundingBoxWkt(geoPoint).then((value) {
        DataManager.instance.dataController
            .snapDataList(value)
            .then((value) {
          if (value.isNotEmpty) {
            if (value.length == 1) {
              showElementEditPage(value[0]);
            } else {
              dataList = value;
              addPage(ElementListPage());
            }
            EventBusUtils.getInstance()
                .fire(ChangeBottomDrawerStatus(DragStatus.stateHalfExpanded));
          }
        });
      });
    });
  }

  ///获取所有数据图层
  Future getDataLayerList() async {
    dataLayerList =
        await DataManager.instance.dataController.queryDataLayerList();
    projectList =
        await DataManager.instance.dataController.queryDataProjectList();
    addPage(LayerListPage());
  }

  ///创建底图设置页面
  void createBaseMapSettingPage() {
    MapManager.instance.mapController.getRasterTileLayerList().then((value) {
      layerList = value;
      if (layerList.isNotEmpty) {
        for (int i = 0; i < layerList.length; i++) {
          layerList[i].imagePath = i % 2 == 0
              ? "assets/btn_2d_ditu_n.png"
              : "assets/btn_gaofenyingxiang_n.png";
          //第一个为默认底图
          if (i == 0 && selectLayer?.url == null) {
            layerList[i].isSelect = true;
          } else {
            if (layerList[i].url == selectLayer?.url) {
              layerList[i].isSelect = true;
            }
          }
        }
      }
      List<String>? list = SpHelper.getStringList("otherLayer");
      for (int i = 0; i < list.length; i++) {
        otherLayerList.add(NIRasterTileLayer.fromJson(list[i]));
      }
      BaseMapSettringPage page = BaseMapSettringPage();
      addPage(page);
      EventBusUtils.getInstance()
          .fire(ChangeBottomDrawerStatus(DragStatus.stateHalfExpanded));
    });
  }

  ///创建选中
  void setSelectLayer(NIRasterTileLayer layer) {
    selectLayer = layer;

    if (layerList.isNotEmpty) {
      for (int i = 0; i < layerList.length; i++) {
        if (layerList[i] == layer) {
          layerList[i].isSelect = !layer.isSelect!;
        } else {
          layerList[i].isSelect = false;
        }
      }
    }

    if (otherLayerList.isNotEmpty) {
      for (int i = 0; i < otherLayerList.length; i++) {
        if (otherLayerList[i] == layer) {
          otherLayerList[i].isSelect = !layer.isSelect!;
        } else {
          otherLayerList[i].isSelect = false;
        }
      }
    }

    notifyListeners();
  }

  ///增加自定义图层
  void showOtherLayerDialog(String name, String url) {
    showDialog(
        barrierDismissible: false,
        context: _mapTitleBarContext,
        builder: (BuildContext build) {
          return MyLayerDialog(
            name: name,
            url: url,
            callBack: (oldName, newName, url) {
              if (saveOtherLayer(oldName, newName, url)) {
                Navigator.maybePop(_mapTitleBarContext);
              }
            },
          );
        });
  }

  //保存自定义图层
  bool saveOtherLayer(String oldName, String newName, String url) {
    if (otherLayerList.isNotEmpty) {
      for (int i = 0; i < otherLayerList.length; i++) {
        if (otherLayerList[i].title == oldName) {
          otherLayerList.removeAt(i);
          break;
        }
      }
    }
    if (otherLayerList.length == 8) {
      Fluttertoast.showToast(msg: "不能超过8条");
      return false;
    }
    if (otherLayerList.isNotEmpty) {
      for (int i = 0; i < otherLayerList.length; i++) {
        if (otherLayerList[i].title == newName) {
          Fluttertoast.showToast(msg: "与其他自定义图层名称重复");
          break;
        }
        if (otherLayerList[i].url == url) {
          Fluttertoast.showToast(msg: "与其他自定义图层地址重复");
          return false;
        }
      }
    }
    NIRasterTileLayer layer = NIRasterTileLayer(
        title: newName,
        url: url,
        imagePath: "assets/btn_2d_ditu_n.png",
        tilePath: "",
        cache: false,
        isSelect: false,
        isDel: true);
    otherLayerList.add(layer);
    List<String> list = [];
    otherLayerList.map((e) => list.add(e.toJson()));
    SpHelper.putStringList("otherLayer", list);
    notifyListeners();
    return true;
  }

  //是否删除
  void setDelLayer() {
    if (!isDelLayer && otherLayerList.isEmpty) {
      Fluttertoast.showToast(msg: "无可删除数据");
      return;
    }
    isDelLayer = !isDelLayer;
    notifyListeners();
  }

  ///切换底图
  void switchNIRasterTileLayer(NIRasterTileLayer layer) {
    if (layer.isSelect == true) {
      MapManager.instance.mapController.removeRasterTileLayer(layer.url!);
    } else {
      MapManager.instance.mapController
          .switchRasterTileLayer(url: layer.url, tilePath: layer.tilePath);
      Fluttertoast.showToast(msg: "设置成功");
    }
    setSelectLayer(layer);
  }

  //删除图层
  void removeLayer(NIRasterTileLayer layer) {
    showDialog(
        barrierDismissible: true,
        context: _mapTitleBarContext,
        builder: (BuildContext build) {
          return MyDialog(
              callback: (value) {
                if (otherLayerList.isNotEmpty) {
                  for (int i = 0; i < otherLayerList.length; i++) {
                    if (otherLayerList[i] == layer) {
                      otherLayerList.remove(layer);
                    }
                  }
                  if (otherLayerList.isEmpty) {
                    isDelLayer = false;
                  }
                }

                notifyListeners();
              },
              title: "提示",
              content: "确定删除自定义地图？");
        });
  }

  ///抽屉增加下级页面
  void addPage(BasePage page) {
    if (curPage == null ||
        curPage.runtimeType.toString() != page.runtimeType.toString()) {
      pageList.add(page);
      curPage = page;
      _setMapTitleBar();
    } else {
      curPage!.update();
    }
    notifyListeners();

    LogUtil.instance.printf("更新抽屉页面", tag: "Provider");
  }

  ///页面返回上一级
  void backPage() {
    var lastPage = curPage;
    curPage?.dispose();
    pageList.removeAt(pageList.length - 1);
    if (pageList.isNotEmpty) {
      curPage = pageList[pageList.length - 1];
      _setMapTitleBar();
      LogUtil.instance.printf("更新返回按钮", tag: "Provider");
      notifyListeners();
      if (lastPage is EditDataPage) {
        curDataLayer = null;
        curElementBean = null;
        lastPage = null;
      }
    } else {
      closeDrawer();
    }
  }

  ///创建属性页面
  void createElementEditPage(DataLayer dataLayer) {
    curDataLayer = dataLayer;
    EditDataPage page = EditDataPage();
    addPage(page);
  }

  ///展示属性页面
  void showElementEditPage(ElementBean data) {
    curElementBean = data;
    if (curElementBean != null) {
      DataManager.instance.dataController
          .queryDataLayer(curElementBean!.layerId)
          .then((value) {
        if (value != null) {
          for (var item in value.itemList) {
            if (data.values.containsKey(item.key)) {
              item.value = data.values[item.key];
            }
          }
          curDataLayer = value;

          if (value.geometryType == GeometryType.geometryTypePoint) {
            NIGeoPoint? point = GeometryTool.getGeoPintFromWkt(data.geometry);
            if (point != null) {
              MapManager.instance.addMarker(point);
            }
            addPage(EditDataPage());
          }
        }
      });
    }
  }

  ///关闭抽屉
  ///[isActive] 是否是用户通过按钮主动触发
  ///如果是主动触发，通知抽屉收起就行了，抽屉不用再通知[DrawerManagerViewModel]进行页面管理
  ///反之：来自抽屉的被动触发，不用再给抽屉发消息，它知道该怎么办，[DrawerManagerViewModel]自己管理好页面状态就行了
  void closeDrawer({bool isActive = true}) {
    if (isActive) {
      EventBusUtils.getInstance()
          .fire(ChangeBottomDrawerStatus(DragStatus.stateClose));
    } else {
      for (var page in pageList) {
        page.dispose();
      }
      pageList.clear();
      curPage = null;
      mapTitleBarAdapter = null;
      notifyListeners();
      curDataLayer = null;
      curElementBean = null;
    }
  }

  ///设置地图顶部状态栏
  void _setMapTitleBar() {
    mapTitleBarAdapter = curPage!.getMapTitleBarAdapter(_mapTitleBarContext);
  }

  ///保存数据
  void saveData() {
    String wkt = "";
    Map<String, dynamic> values = {};

    ///获取修改几何坐标
    switch (curDataLayer?.geometryType) {
      case GeometryType.geometryTypePoint:
        if (MapManager.instance.niMarker == null) {
          Fluttertoast.showToast(msg: "没有选取点位");
          return;
        } else {
          wkt =
              GeometryTool.getPointWkt(MapManager.instance.niMarker!.geoPoint);
        }
        break;
      case GeometryType.geometryTypeLine:
        if (MapManager.instance.points.isEmpty) {
          Fluttertoast.showToast(msg: "没有选取点位");
          return;
        }else if(MapManager.instance.points.length<2){
          Fluttertoast.showToast(msg: "至少2个点");
          return;
        }else{
          wkt = GeometryTool.getLineWkt(MapManager.instance.points);
        }
        break;
      case GeometryType.geometryTypePolygon:
        if (MapManager.instance.points.isEmpty) {
          Fluttertoast.showToast(msg: "没有选取点位");
          return;
        }else if(MapManager.instance.points.length<3){
          Fluttertoast.showToast(msg: "至少3个点");
          return;
        }else{
          wkt = GeometryTool.getPolygonWkt(MapManager.instance.points);
        }
        break;
    }

    ///新增或修改
    if (curElementBean == null) {
      curElementBean = ElementBean(
        geometry: wkt,
        layerId: curDataLayer!.uuid,
        tOperateDate: StringUtil.formatCurrentTime(),
        values: values,
      );
    } else {
      curElementBean!.geometry = wkt;
      curElementBean!.tOperateDate = StringUtil.formatCurrentTime();
      curElementBean!.tStatus = 1;
      curElementBean!.tLifecycle = 2;
      curElementBean!.values = values;
    }

    for (var item in curDataLayer!.itemList) {
      values.putIfAbsent(item.key, () => item.value);
      if (item.isMainName) {
        curElementBean?.displayText = item.value;
      }
    }

    DataManager.instance.dataController
        .saveElementData(curElementBean!)
        .then((value) {
      if (value == "true") {
        MapManager.instance.mapController.upDateMap(redraw: true);
        backPage();
      }
    });
  }

  ///在地图上打点
  void addPoint() {
    switch (curDataLayer?.geometryType) {
      case GeometryType.geometryTypePoint:
        MapManager.instance.addMarkerByForesight();
        break;
      case GeometryType.geometryTypeLine:
        MapManager.instance.addDrawLinePointByForesight();
        break;
      case GeometryType.geometryTypePolygon:
        MapManager.instance.addDrawPolygonPointByForesight();
        break;
    }
  }

  void setCurItemValue(dynamic value) {
    curItem?.value = value;
    notifyListeners();
    backPage();
  }
}

///用于event_bus 对外广播抽屉状态
///抽屉状态更新，通知其他控件
class BottomDrawerStatusChange {
  DragStatus status = DragStatus.stateClose;

  BottomDrawerStatusChange(this.status);
}

///其他控件通知抽屉变化
class ChangeBottomDrawerStatus {
  DragStatus status = DragStatus.stateClose;

  ChangeBottomDrawerStatus(this.status);
}

///用于event_bug 对外广播抽屉高度，动画比例
class ChangeBottomDrawerTop {
  double top = 0;
  double animalControllerVale = 0;

  ChangeBottomDrawerTop(this.top, this.animalControllerVale);
}
